package com.example.userdepartment.service.impl;

import com.example.userdepartment.entity.Department;
import com.example.userdepartment.mapper.DepartmentMapper;
import com.example.userdepartment.service.DepartmentService;
import com.example.userdepartment.util.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门服务实现类
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    private static final Logger logger = LoggerFactory.getLogger(DepartmentServiceImpl.class);

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> findAll() {
        return departmentMapper.selectAll();
    }

    @Override
    public Department findById(Integer id) {
        return departmentMapper.selectById(id);
    }

    @Override
    public Department findWithUsersById(Integer id) {
        return departmentMapper.selectWithUsersById(id);
    }

    @Override
    @Transactional
    public Department add(Department department) {
        departmentMapper.insert(department);
        return department;
    }

    @Override
    @Transactional
    public Department update(Department department) {
        departmentMapper.update(department);
        return departmentMapper.selectById(department.getId());
    }

    @Override
    @Transactional
    public boolean delete(Integer id) {
        return departmentMapper.delete(id) > 0;
    }

    @Override
    @Transactional
    public boolean batchDelete(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return departmentMapper.batchDelete(ids) > 0;
    }

    @Override
    public List<Department> searchDepartments(String keyword) {
        logger.info("搜索部门 - 关键字: {}", keyword);
        
        // 如果关键字为空，则返回所有部门
        if (keyword == null || keyword.trim().isEmpty()) {
            return findAll();
        }
        
        // 根据关键字搜索
        String lowerKeyword = keyword.toLowerCase().trim();
        List<Department> allDepartments = findAll();
        return allDepartments.stream()
                .filter(dept -> 
                    (dept.getName() != null && dept.getName().toLowerCase().contains(lowerKeyword)) ||
                    (dept.getDescription() != null && dept.getDescription().toLowerCase().contains(lowerKeyword))
                )
                .collect(Collectors.toList());
    }

    @Override
    public byte[] exportDepartments() {
        try {
            List<Department> departments = departmentMapper.selectAll();
            // 查询每个部门的用户信息
            for (Department department : departments) {
                if (department.getId() != null) {
                    Department deptWithUsers = departmentMapper.selectWithUsersById(department.getId());
                    if (deptWithUsers != null && deptWithUsers.getUsers() != null) {
                        department.setUsers(deptWithUsers.getUsers());
                    }
                }
            }
            return ExcelUtil.exportDepartmentData(departments);
        } catch (IOException e) {
            logger.error("导出部门Excel出错", e);
            throw new RuntimeException("导出部门Excel出错: " + e.getMessage());
        }
    }
} 